package yu.code.yurpc.server.tcp;

import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetServer;
import io.vertx.core.parsetools.RecordParser;
import yu.code.yurpc.server.HttpServer;

/**
 *
 */
public class VertxTcpServer implements HttpServer {
    private byte[] handleRequest(byte[] request) {
        return "Hello,client".getBytes();
    }

    @Override
    public void start(int port) {
        //创建 vertx实例
        Vertx vertx = Vertx.vertx();
        //创建TCP服务器
        NetServer server = vertx.createNetServer();
        //处理请求
        server.connectHandler(socket -> {
            //处理连接
            //构造parser
            RecordParser recordParser = RecordParser.newFixed(8);
            recordParser.setOutput(new Handler<Buffer>() {
                //初始化
                int size = -1;
                //一次完整的读取（头+体）
                Buffer resultBuffer = Buffer.buffer();

                @Override
                public void handle(Buffer buffer) {
                    if (-1 == size) {
                        //读取消息体长度
                        size = buffer.getInt(4);
                        recordParser.fixedSizeMode(size);
                        //写入头信息到结果
                        resultBuffer.appendBuffer(buffer);
                    } else {
                        //写入体信息到结果
                        resultBuffer.appendBuffer(buffer);
                        System.out.println(resultBuffer.toString());
                        //重置一轮
                        recordParser.fixedSizeMode(8);
                        size = -1;
                        resultBuffer = Buffer.buffer();
                    }
                }
            });
            socket.handler(recordParser);
        });
        //启动TCP服务器监听指端端口
        server.listen(port, result -> {
            if (result.succeeded()) {
                System.out.println("Server started on port " + port);
            } else {
                System.out.println("Failed to start server");
            }
        });

    }

    public static void main(String[] args) {
        VertxTcpServer server = new VertxTcpServer();
        server.start(8888);
    }
}
